package com.example.cdpbookstore.web.servlet;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.example.cdpbookstore.constant.FilePath;
import com.example.cdpbookstore.pojo.entity.Customer;
import com.example.cdpbookstore.pojo.entity.Result;
import com.example.cdpbookstore.service.CustomerService;
import com.example.cdpbookstore.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet("/update/*")
@MultipartConfig // JavaScript的fetch() 默认 multipart/form-data格式数据，需要@MultipartConfig 注解
public class CustomerUpdateServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getPathInfo().substring(1);
        Customer customer = (Customer) req.getSession().getAttribute("customer");

        switch (action) {
            case "recipient":
                updateRecipient(req, resp, customer);
                break;
            case "avatar":
                updateAvatar(req, resp, customer);
                break;
            case "email":
                updateEmail(req, resp, customer);
                break;
            case "password":
                updatePassword(req, resp, customer);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


    private void updateRecipient(HttpServletRequest req, HttpServletResponse resp, Customer customer) throws ServletException, IOException {
        String name = req.getParameter("rec-name");
        String mobile = req.getParameter("rec-mobile");
        String address = req.getParameter("rec-address");

        customer.setName(name);
        customer.setMobile(mobile);
        customer.setAddress(address);

        customerService.update(customer);
        responseJson(resp, "收件人信息修改成功");
    }

    private void updateAvatar(HttpServletRequest req, HttpServletResponse resp, Customer customer) throws ServletException, IOException {
        Part part = req.getPart("ava-new");
        String fileName = part.getSubmittedFileName();

        if (fileName != null && !fileName.trim().isEmpty()) {
            fileName = IdUtil.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            customer.setAvatar(fileName);

            customerService.update(customer);

            // 图片写入磁盘
            part.write(FilePath.IMAGE + "/avatar/" + fileName);
            responseJson(resp, "头像修改成功");
        }
    }

    private void updateEmail(HttpServletRequest req, HttpServletResponse resp, Customer customer) throws ServletException, IOException {
        String email = req.getParameter("email-new");
        String captchaInput = req.getParameter("captcha");
        Object captchaSession = req.getSession().getAttribute("captcha");

        if (!Objects.equals(captchaInput, captchaSession)) {

            System.out.println("updateEmail() 验证码错误");
            responseJson(resp, "验证码错误");
            return;
        }

        customer.setEmail(email);

        customerService.update(customer);
        responseJson(resp, "邮箱修改成功");
    }

    private void updatePassword(HttpServletRequest req, HttpServletResponse resp, Customer customer) throws ServletException, IOException {
        String passwordOld = req.getParameter("pas-old");
        String passwordNew = req.getParameter("pas-new");

        // 比对密码
        if (!BCrypt.checkpw(passwordOld, customer.getPassword())) {
            // 输入的旧密码错误
            System.out.println("updatePassword() 输入的旧密码错误");
            responseJson(resp, "输入的旧密码错误");
            return;
        }

        customer.setPassword(BCrypt.hashpw(passwordNew, BCrypt.gensalt()));

        customerService.update(customer);
        responseJson(resp, "密码修改成功");
    }


    private void responseJson(HttpServletResponse response, String msg) throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String json = JSONUtil.toJsonStr(Result.message(msg));
        out.println(json);
        out.flush();
        out.close();
    }

}
